//
//  WQRequestHelper.swift
//  AddressInput
//
//  Created by huwenqiang on 2019/9/10.
//  Copyright © 2019 huwenqiang. All rights reserved.
//

import Foundation
import Alamofire
import CommonCrypto

typealias WQRequestSucceed = (_ data:Any) ->Void
typealias WQRequestError = (_ error:Error) ->Void

class WQRequestHelper: NSObject {
    
    static public func request(param:[String: String], method:HTTPMethod, apiName:String, succeed:@escaping WQRequestSucceed, error:@escaping WQRequestError) {
        WQRequestHelper.request(baseUrl: "http://gw.api.taobao.com/router/rest", param: param, method: method, apiName: apiName,isExpra:true, succeed: succeed, requestError: error)
    }
    
    static public func request(baseUrl:String, param:[String: String], method:HTTPMethod, apiName:String, isExpra:Bool, succeed:@escaping WQRequestSucceed, requestError:@escaping WQRequestError) {
        var mparam = param
        if isExpra {
            mparam.updateValue(apiName, forKey: "method")
            mparam.updateValue(AppKey, forKey: "app_key")
            mparam.updateValue("md5", forKey: "sign_method")
            let timestamp = WQRequestHelper.formatTimeStamp(time: Int(Date.init().timeIntervalSince1970), format: "yyyy-MM-dd HH:mm:ss")
//            print(timestamp)
            mparam.updateValue(timestamp, forKey: "timestamp")
            mparam.updateValue("2.0", forKey: "v")
            mparam.updateValue("json", forKey: "format")
            
            let sign = self.createSign(publicParam: mparam)
            mparam.updateValue(sign, forKey: "sign")
        }
        
        Alamofire.request(baseUrl, method: method, parameters: mparam).responseJSON { (response) in
//            print(response.value as Any)
            switch response.result {
            case .success(let value):
                succeed(value)
            case .failure(let error):
                print("请求失败详情 -> : \(error)")
                requestError(error)
            }
            
        }
        
    }
    
    static public func requestOnlyUrl(url:String, succeed:@escaping WQRequestSucceed, requestError:@escaping WQRequestError) {
        Alamofire.request(URL.init(string: url)!).responseJSON { (response) in
//            print(response.value as Any)
            switch response.result {
            case .success(let value):
                    succeed(value)
            case .failure(let error):
                print("请求失败详情 -> : \(error)")
                requestError(error)
            }
        }
    }
    /// 获取淘宝商品详情
    /// - Parameter goodId: 商品ID
    /// - Parameter method: get

    /// - Parameter succeed: 成功
    static public func requestGoodDetailTB(goodId:Int, method:HTTPMethod, succeed:@escaping WQRequestSucceed, error: @escaping WQRequestError) {
        let strUrl = "https://acs.m.taobao.com/h5/mtop.taobao.detail.getdetail/6.0/"
//        print(strUrl)
        WQRequestHelper.request(baseUrl: strUrl, param: ["data":"{\"itemNumId\":\"\(goodId)\"}"], method: method, apiName: "",isExpra:false, succeed: succeed, requestError: error)
    }
    
    
    static func formatTimeStamp(time:Int ,format:String) -> String {
        let timeInterval = TimeInterval(time)
        let date = Date.init(timeIntervalSince1970: timeInterval)
        let dateFormatte = DateFormatter()
        dateFormatte.dateFormat = format
        return dateFormatte.string(from: date)
    }
    
    static func createSign(publicParam:[String: String]) -> String {
        let after = publicParam.sorted { (arg0, arg1) -> Bool in
            if(arg0.key < arg1.key) {
                    return false
            }
            return true
        }
        var tempString = ""
        for (key,value) in after.reversed() {
            tempString += key;
            tempString += value
        }
//        print(tempString)
        let secretKey = AppSecret
        let secretResult = WQRequestHelper.md5(strs: secretKey + tempString + secretKey)
        return secretResult.uppercased()
    }
    
    static func md5(strs:String) ->String {
      let str = strs.cString(using: String.Encoding.utf8)
      let strLen = CUnsignedInt(strs.lengthOfBytes(using: String.Encoding.utf8))
      let digestLen = Int(CC_MD5_DIGEST_LENGTH)
      let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
      CC_MD5(str!, strLen, result)
      let hash = NSMutableString()
      for i in 0 ..< digestLen {
          hash.appendFormat("%02x", result[i])
      }
      return String(format: hash as String)
    }
}
